# Create your views here.

import string
from django.shortcuts           import render_to_response
from djangobb.forums.models     import Forum, Topic, Post, Tag, Cites
from djangobb.forums.forumforms import TopicForm, ForumForm, PostForm
from djangobb.utils             import common_funcs


def page_to_nums(pageNum):
    startNum   = pageNum * 10
    endNum     = (pageNum+1) * 10
   
    return (startNum, endNum)

def adjust_nums(startNum, endNum, num):
    if num == 0 or startNum >= num:
        startNum = 0
        endNum   = 0
    else:
        endNum = num - startNum
        startNum += 1 

    return (startNum, endNum)

def fill_page_vars(pageNum, totalNum):
    page_vars = {} 
    page_vars['current_page'] = pageNum 
    maxPages = int(totalNum/10.0)

    if pageNum >= 10: 
        startPage = pageNum - 5
        endPage   = pageNum + 5
    else:
        startPage = 0 
        endPage   = 9 

    if endPage > maxPages:
        endPage = maxPages

    if pageNum > 0:
        page_vars['prev_page'] = pageNum - 1 
 
    if pageNum < maxPages:
        page_vars['next_page'] = pageNum + 1

    pages = []
    for i in range(startPage, endPage + 1):
        pages.append(i)
    page_vars['pages'] = pages

    return page_vars


def mainpage(request, pageNumStr='0'):
    forums  = common_funcs.get_forums()
    uname   = common_funcs.get_uname(request)
    isStaff = common_funcs.is_staff(request)

    pageNum = string.atoi(pageNumStr)
    (startNum, endNum) = page_to_nums(pageNum)

    numTopics = Topic.objects.count()
    try:
        topics     = Topic.objects.order_by('-startTime')[startNum:endNum]
    except:
        topics     = []

    # get variables for generating page limits
    page_vars  = fill_page_vars(pageNum, numTopics)
    htmlInfo   = {'forums': forums, 'isStaff': isStaff, 'uname': uname, \
                  'page_url': '/cms/forums', 'topics': topics, \
                  'page_vars': page_vars, 'nextpage': request.path,\
                  'title': 'Discuss Indian laws and court judgments',\
                  'nextpage': request.path}

    return render_to_response('forums.html', htmlInfo)

def viewforum(request, forumIdStr, pageNumStr='0'):
    forumId = string.atoi(forumIdStr)
    pageNum = string.atoi(pageNumStr)
    (startNum, endNum) = page_to_nums(pageNum)

    # get forum information
    try:
        forumObj = Forum.objects.filter(id=forumId).get()
        totalNum = Topic.objects.filter(forumId=forumId).count()
    except:
        return render_to_response('msg.html', \
            {'msg': 'Could not find this forum', 'goback':'/cms/forums/'})

    if totalNum > 0 and startNum < totalNum:
        # use django database API
        try:
            topics     = Topic.objects.filter(forumId=forumId).order_by('-startTime')[startNum:endNum]
        except:
            topics     = []
    else:
        topics = []
    numTopics = len(topics)
    (startNum, endNum) = adjust_nums(startNum, endNum, numTopics)

    forums  = common_funcs.get_forums() 
    uname   = common_funcs.get_uname(request)
    isStaff = common_funcs.is_staff(request)
    page_vars  = fill_page_vars(pageNum, numTopics)
    htmlInfo = {'forums': forums, 'nextpage': request.path, 'forum': forumObj,\
                'topics': topics, 'uname': uname, 'isStaff': isStaff, \
                'page_url': '/cms/forums/viewforum/%d' % forumId, \
                'page_vars': page_vars, \
                'title': forumObj.title, 'nextpage': request.path}
 
    return render_to_response('viewforum.html', htmlInfo)
  
def viewtopic(request, topicIdStr, pageNumStr='0'):
    topicId = string.atoi(topicIdStr)
    pageNum = string.atoi(pageNumStr)
    (startNum, endNum) = page_to_nums(pageNum)
   
    # get topic info
    try:
        topic    = Topic.objects.get(id=topicId)
        totalNum = Post.objects.filter(topicId=topicId).count()
    except:
        return render_to_response('msg.html', {'msg': 'Could not find this topic', 'goback': '/cms/forums/'})

    forumObj = Forum.objects.get(id=topic.forumId_id)
     # get posts with in a topic 
    if totalNum > 0 and startNum < totalNum and startNum < endNum:
        # use django database API
        try:
            posts = Post.objects.filter(topicId=topicId).order_by('postTime')[startNum:endNum]
        except:
            posts = []
    else:
        posts = [] 

    forums  = common_funcs.get_forums() 
    uname   = common_funcs.get_uname(request)
    isStaff = common_funcs.is_staff(request)

    # get variables for page numbers
    page_vars = fill_page_vars(pageNum, totalNum)
    htmlInfo = {'nextpage': request.path, 'topic': topic, 'posts': posts,\
                'uname': uname, 'page_vars': page_vars, 'isStaff': isStaff,\
                'forums': forums, 'forum': forumObj, 'title': topic.title, \
                'page_url': '/cms/forums/viewtopic/%d' % topicId}

    return render_to_response('viewtopic.html', htmlInfo)

def newforum(request):
    nextPage = common_funcs.get_next_page(request)
    remoteIp = request.META['REMOTE_ADDR']
    
    forums  = common_funcs.get_forums() 
    uname   = common_funcs.get_uname(request)
    isStaff = common_funcs.is_staff(request)

    htmldict = {'forums': forums, 'uname': uname}
    if request.user.is_authenticated() and isStaff and request.method == 'POST':
        forumForm = ForumForm(remoteIp, request.POST)
        htmldict['form'] = forumForm 
        if not forumForm.is_valid():
            return render_to_response('newforum.html', htmldict)
        # a staff is creating a forum
        cleanData = forumForm.clean()
        title     = cleanData['title']
        desc      = cleanData['desc']
        imp       = cleanData['imp'] 
        newForum = Forum(title = title, description = desc, importance = imp)
        try:
            newForum.save()
        except:
            return render_to_response('newforum.html', htmldict)

        htmldict['msg']    = 'Successfully created the forum titled %s.' % title 
        htmldict['goback'] =  nextPage
        return render_to_response('msg.html', htmldict) 
    else:
        htmldict['form'] = forumForm 
        forumForm = ForumForm(remoteIp) 
        return render_to_response('newforum.html', htmldict)
 
def newtopic(request, forumIdStr):
    nextPage = common_funcs.get_next_page(request)
    remoteIp = request.META['REMOTE_ADDR']

    uname   = common_funcs.get_uname(request)
    forums  = common_funcs.get_forums()
    htmldict = {'forums': forums, 'uname': uname, 'nextpage': nextPage}

    forumId = string.atoi(forumIdStr)

    try:
       forum    = Forum.objects.filter(id = forumId).get()
    except:
       htmldict['msg']    = 'No such forum to post this topic'
       htmldict['goback'] =  nextPage
       return render_to_response('msg.html', htmldict)

    htmldict['forum'] = forum
    if request.method == 'POST':
        topicForm = TopicForm(remoteIp, request.POST)
        htmldict['form']  = topicForm
        if not topicForm.is_valid():
            return render_to_response('newtopic.html', htmldict)

        # everything fine, create the topic 
        cleanData = topicForm.clean()
        title     = cleanData['title']
        desc      = cleanData['desc']
        tags      = cleanData['tags']
        tids      = cleanData['tids']

        newTopic = Topic(forumId = forum, uname = uname, title = title, text=desc)
        try:
            newTopic.save()
            newPost  = Post(topicId = newTopic, uname = uname, title = title, text = desc)
            newPost.save()
        except: 
            htmldict['form']  = topicForum
            return render_to_response('newtopic.html',  htmldict)

        # save the tags 
        tagList = string.split(tags, ',')
        level = 0
        for tagName in tagList:
            if len(tagName) > 0:
                tag = Tag(topicId=newTopic, tagLevel=level, tagName=tagName)
                tag.save()
                level += 1 
        # save the cites 
        citesList = string.split(tids, ',')
        for tidStr in citesList:
            try:
                tid = string.atoi(tidStr)
                cite = Cites(topicId=newTopic, tid=tid)
                cite.save()
            except ValueError:
                pass
        # successful
        htmldict['goback'] = nextPage 
        htmldict['msg']    =  'Started a new topic with title "%s" in %s' % (title, forum.title)
        return render_to_response('msg.html', htmldict)
    else:   
        if request.GET.has_key('tids'):
            tids = request.GET['tids']
            topicForm = TopicForm(remoteIp, {'title': '', 'desc': '', 'tags': '', 'tids': tids})
        else:
            topicForm = TopicForm(remoteIp)
        htmldict['form'] = topicForm
        return render_to_response('newtopic.html', htmldict)
    
def newpost(request,  topicIdStr):
    remoteIp = request.META['REMOTE_ADDR']
    nextPage = common_funcs.get_next_page(request)
    uname   = common_funcs.get_uname(request)
    forums  = common_funcs.get_forums()
    htmldict = {'forums': forums, 'uname': uname, 'nextpage': nextPage}

    topicId = string.atoi(topicIdStr)
    try:
        topic = Topic.objects.filter(id = topicId).get()
    except:
       htmldict['msg']    = 'No such topic to post'
       htmldict['goback'] = nextPage
       return render_to_response('msg.html', htmldict)

    htmldict['topic'] = topic
    if request.method == 'POST':
        postForm = PostForm(remoteIp, request.POST)
        htmldict['form'] = postForm
        if not postForm.is_valid():
            return render_to_response('newpost.html', htmldict) 

        cleanData = postForm.clean()
        title     = cleanData['title']
        desc      = cleanData['desc']
        newPost  = Post(topicId = topic, uname = uname, title = title, text = desc)
        try:
            newPost.save()
        except:
            return render_to_response('newpost.html', htmldict)

        # Success
        htmldict['msg']    = 'Posted message with title "%s" in the topic "%s".' % (title, topic.title) 
        htmldict['goback'] = nextPage
        return render_to_response('msg.html', htmldict)
    else:
        postForm = PostForm(remoteIp)
        htmldict['form'] = postForm
    return render_to_response('newpost.html', htmldict) 

# DELETE POSTS
# Only staff can delete posts

def deleteforum(request, forumIdStr):
    nextPage = common_funcs.get_next_page(request)
    uname    = common_funcs.get_uname(request)
    forums   = common_funcs.get_forums()
    htmldict = {'forums': forums, 'uname': uname, 'nextpage': nextPage, \
                'goback': nextPage}

    if request.user.is_authenticated and request.user.is_staff:
        nextPage = common_funcs.get_next_page(request)
        forumId = string.atoi(forumIdStr)
        forumObj = Forum.objects.get(id=forumId)
        if forumObj != None:
            forumObj.delete()
            htmldict['msg']    = 'Successfully deleted the forum'
            htmldict['goback'] = nextPage
            return render_to_response('msg.html', htmldict)
        else:
            htmldict['msg']    = 'Could not find the forum to delete'
            return render_to_response('msg.html', htmldict)
    else: 
        htmldict['msg']    = 'Only staff can delete  a forum' 
        return render_to_response('msg.html', htmldict)

def deletetopic(request, topicIdStr):
    nextPage = common_funcs.get_next_page(request)
    uname    = common_funcs.get_uname(request)
    forums   = common_funcs.get_forums()
    htmldict = {'forums': forums, 'uname': uname, 'nextpage': nextPage, \
                'goback': nextPage}

    if request.user.is_authenticated and request.user.is_staff:
        nextPage = common_funcs.get_next_page(request)
        topicId = string.atoi(topicIdStr)
        topicObj = Topic.objects.get(id=topicId)
        if topicObj != None:
            topicObj.delete()
            htmldict['msg'] =  'Successfully deleted the thread'
            return render_to_response('msg.html', htmldict)
        else:
            htmldict['msg'] = 'Could not find the thread to delete'
            return render_to_response('msg.html', htmldict)
    else: 
        htmldict['msg'] = 'Only staff can delete a thread' 
        return render_to_response('msg.html', htmldict)

def deletepost(request, postIdStr):
    nextPage = common_funcs.get_next_page(request)
    uname    = common_funcs.get_uname(request)
    forums   = common_funcs.get_forums()
    htmldict = {'forums': forums, 'uname': uname, 'nextpage': nextPage, \
                'goback': nextPage}

    if request.user.is_authenticated and request.user.is_staff:
        postId = string.atoi(postIdStr)
        postObj = Post.objects.get(id=postId)
        if postObj != None:
            postObj.delete()
            htmldict['msg'] = 'Successfully deleted the post'
            return render_to_response('msg.html', htmldict)
        else:
            htmldict['msg'] = 'Could not find the post to delete'
            return render_to_response('msg.html', htmldict)
    else: 
        htmldict['msg'] = 'Only staff can delete a post'
        return render_to_response('msg.html', htmldict)
